package com.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.spi.DirStateFactory.Result;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class Jndilook
 */
public class Jndilook extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Jndilook()
    {
        super();
        // TODO Auto-generated constructor stub
    }
    
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        System.out.println(System.getenv(javax.naming.Context.INITIAL_CONTEXT_FACTORY));
        System.out.println(System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY));
        Context ic = null;
        try
        {
            ic = new InitialContext();
        }
        catch (NamingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        DataSource source = null;
        try
        {
//            Context envContext = (Context) ic.lookup("java:/comp/env");
//            source = (DataSource) envContext.lookup("jdbc/TestDB");
//            Context envContext = (Context) ic.lookup("java:/comp/env");
          source = (DataSource) ic.lookup("java:/comp/env/jdbc/TestDB");
        }
        catch (NamingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try
        {
            Connection con = source.getConnection();
            Statement s = con.createStatement();
            ResultSet rs = s.executeQuery("select * from blog");
            rs.next();
            System.out.println("==========="+rs.getString(2));
        }
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
    
}
